package com.example.four;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import com.example.four.Yao;

public class MoneyDivinationActivity extends AppCompatActivity {
    private EditText etQuestion;
    private Button btnDivine;
    private TextView tvResult;
    private List<Yao> yaoList = new ArrayList<>();
    private int currentYaoIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_divination);

        etQuestion = findViewById(R.id.et_question);
        btnDivine = findViewById(R.id.btn_divine);
        tvResult = findViewById(R.id.tv_result);

        btnDivine.setOnClickListener(v -> {
            String question = etQuestion.getText().toString().trim();
            if (currentYaoIndex == 0 && question.isEmpty()) {
                etQuestion.setError("请输入您想询问的事情");
                return;
            }

            if (currentYaoIndex < 6) {
                Yao yao = DivinationUtil.tossCoinsOnce();
                yaoList.add(yao);
                currentYaoIndex++;

                // 逐次展示当前爻
                showCurrentYao();

                if (currentYaoIndex == 6) {
                    // 六爻摇完，展示完整卦象和运势解读
                    showFullHexagram();
                    btnDivine.setText("重新摇卦");
                }
            } else {
                // 重新摇卦
                yaoList.clear();
                currentYaoIndex = 0;
                tvResult.setText("");
                tvResult.setVisibility(View.GONE);
                btnDivine.setText("开始摇卦");
            }
        });
    }

    /**
     * 展示当前摇出的单爻
     */
    private void showCurrentYao() {
        if (currentYaoIndex == 1) {
            tvResult.setText("您问的是：" + etQuestion.getText().toString().trim() + "\n\n");
            tvResult.append("🔮 卦象结果（从下到上排列，逐次生成）：\n");
        }
        int position = currentYaoIndex;
        Yao yao = yaoList.get(currentYaoIndex - 1);
        tvResult.append("第" + position + "爻：" + yao.getFormattedSymbol()
                + (yao.isMoving() ? "（动爻）" : "") + "\n");
        tvResult.setVisibility(View.VISIBLE);
    }

    /**
     * 展示完整卦象和运势解读
     */
    private void showFullHexagram() {
        StringBuilder sb = new StringBuilder();
        sb.append("🔮 完整卦象（从下到上排列）：\n");
        for (int i = 0; i < yaoList.size(); i++) {
            int position = i + 1;
            Yao yao = yaoList.get(i);
            sb.append("第" + position + "爻：" + yao.getFormattedSymbol()
                    + (yao.isMoving() ? "（动爻）" : "") + "\n");
        }
        sb.append("\n").append(DivinationUtil.interpretFortune(yaoList));
        tvResult.setText(sb.toString());
    }
}